package com.zhanghu.backendZray.utils.oilPrice;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.zhanghu.backendZray.pojo.dto.oilPrice.OilPriceDTO;
import com.zhanghu.backendZray.pojo.dto.oilPrice.OilPriceResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * 油价工具类
 *
 * @author ZhangDong
 * @date 2025/1/17 17:21
 */
@Slf4j
public class OilPriceUtil {

    /**
     * 获取某地区油价信息
     * 支持地区：北京,上海,江苏,天津,重庆,江西,辽宁,安徽,内蒙古,福建,宁夏,甘肃,青海,广东,山东,广西,山西,贵州,陕西,海南,四川,河北,西藏,河南,新疆,黑龙江,吉林,云南,湖北,浙江,湖南
     * 接口备注：需要设置User-Agent：iamwawa-open-api 。每分钟限请求60次，
     */
    @SneakyThrows
    public static OilPriceDTO getOilPrice(String area) {
        long start = System.currentTimeMillis();
        HttpRequest httpRequest = HttpRequest.get("https://www.iamwawa.cn/oilprice/api?area=" + area);
        httpRequest.header("User-Agent", "iamwawa-open-api");
        HttpResponse execute = httpRequest.execute();
        // 结果：{"status":1,"data":{"date":"2025-01-17","name":"\u5317\u4eac","p98":"9.77","p95":"8.27","p92":"7.77","p0":"7.48","p10":"7.93","p20":"8.30","p35":"8.60","next_update_time":"2025-02-06 24:00"}}
        String body = execute.body();
        // 将"-" 替换为null
        body = body.replaceAll("\"-\"", "null");
        log.info("油价信息查询, result:{}, 耗时:{}ms", body, System.currentTimeMillis() - start);

        OilPriceResponse response = JSON.parseObject(body, OilPriceResponse.class);
        if (response.getStatus() == 1) {
            OilPriceDTO oilPriceDTO = response.getData();
            // 获取name字段并解码
            oilPriceDTO.setName(new String(oilPriceDTO.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
            return oilPriceDTO;
        }
        // todo 如果查询失败，需要发送消息给超管
        return null;
    }

}
